<template>
  <div class="container">
    <template v-if="!isSuccess">
      <h1 style="text-align: center">
        {{ type === "signup" ? "报名" : "签到" }}
      </h1>
      <el-form :model="form" ref="formRef" :rules="rule" label-position="top" style="width: 80%">
        <el-divider content-position="left"></el-divider>
        <el-row>
          <el-form-item prop="staffName" label="姓名" label-width="80px" style="width: 100%">
            <el-input v-model="form['staffName']" /> <!-- 修改处：添加 @input 事件 -->
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="staffIdentity" label="身份证号" label-width="80px" style="width: 100%">
            <el-input v-model="form['staffIdentity']" /> <!-- 修改处：添加 @input 事件 -->
          </el-form-item>
        </el-row>
        <el-row v-if="type === 'signup'">
          <el-form-item prop="phone" label="电话号码" label-width="80px" style="width: 100%">
            <el-input v-model="form['phone']" /> <!-- 修改处：添加 @input 事件 -->
          </el-form-item>
        </el-row>

        <el-row v-if="type === 'signup'">
          <el-form-item prop="provinceId" label="省" label-width="80px" style="width: 100%">
            <!-- <CitySelect v-model="form['provinceId']" key="areaId" @update:model-value="(v) => getAreaLists(v)" /> -->
              <SingleLayerSelect v-model="form['provinceId']" :options="provinceList" @update:modelValue="(v)=>getCityList(v)"/>
          </el-form-item>

        </el-row>

        <el-row v-if="type === 'signup'">
          <el-form-item prop="cityId" label="市" label-width="80px" style="width: 100%">
            <!-- <CitySelect v-model="form['provinceId']" key="areaId" @update:model-value="(v) => getAreaLists(v)" /> -->
              <SingleLayerSelect v-model="form['cityId']" :options="cityList" @update:modelValue="(v)=>getAreaList(v)"/>
          </el-form-item>
        </el-row>

        <el-row v-if="type === 'signup'">
          <el-form-item prop="areaId" label="区" label-width="80px" style="width: 100%">
            <!-- <CitySelect v-model="form['provinceId']" key="areaId" @update:model-value="(v) => getAreaLists(v)" /> -->
              <SingleLayerSelect v-model="form['areaId']" :options="areaList" @update:modelValue="(v)=>getTownList(v)"/>
          </el-form-item>
        </el-row>
        <el-row v-if="type === 'signup'">
          <el-form-item prop="townId" label="乡镇" label-width="80px" style="width: 100%">
            <SingleLayerSelect :options="townList" v-model="form['townId']" />
          </el-form-item>
        </el-row>

        <template v-if="type === 'signup'">
          <el-row v-if="drillInfo.isIdentityCard !== 1">
            <el-form-item prop="identityImg" label="身份证" label-width="80px" style="width: 100%">
              <upload-basic :config="{ limit: 1, multiple: false, showCard: true }" v-model="form['identityImg']" />
            </el-form-item>
          </el-row>
          <el-row v-if="drillInfo.isImage !== 1">
            <el-form-item prop="userImg" label="照片" label-width="80px" style="width: 100%">
              <upload-basic :config="{ limit: 1, multiple: false, showCard: true }" v-model="form['userImg']" />
            </el-form-item>
          </el-row>
        </template>
        <el-row justify="center">
          <el-button type="primary" style="width: 100%" @click="submit">确认</el-button>
        </el-row>
        <el-divider content-position="left"></el-divider>
        <!-- 底部活动信息 -->
        <el-form-item label="主办方" label-width="130px" style="margin-top: 50px;" label-position="right">
          <span>{{ drillInfo.drillSponsor }}</span>
        </el-form-item>
        <el-form-item label="协办方" label-width="130px" label-position="right">
          <span>{{ drillInfo.drillAssist }}</span>
        </el-form-item>
        <el-form-item label="联系人1/联系电话1" label-width="140px" label-position="right">
          <span>{{ `${drillInfo.contactsOne} / ${drillInfo.contactsOnePhone}` }}</span>
        </el-form-item>
        <el-form-item label="联系人2/联系电话2" label-width="140px" label-position="right">
          <span>{{ `${drillInfo.contactsTwo} / ${drillInfo.contactsTwoPhone}` }}</span>
        </el-form-item>
        <el-form-item label="地址" label-width="130px" label-position="right">
          <span>{{ drillInfo.address }}</span>
        </el-form-item>
        <el-form-item label="时间" label-width="130px" label-position="right">
          <span>{{ `${drillInfo.startTime}~${drillInfo.endTime}` }}</span>
        </el-form-item>
        <el-form-item label="活动议程" label-width="130px">
          <span>{{ drillInfo.drillAgenda }}</span>
        </el-form-item>
      </el-form>
    </template>

    <!-- 报名签到结果页 -->
    <div style="width: 90%" v-else>
      <h1 style="text-align: center">
        {{ type === "signup" ? "报名成功" : "签到成功" }}
      </h1>
      <el-form>
        <el-form-item label="姓名" label-width="130px">
          <el-input :model-value="userInfo['staffName']" disabled />
        </el-form-item>
        <el-form-item label="身份证号" label-width="130px">
          <el-input :model-value="userInfo['staffIdentity']" disabled />
        </el-form-item>
        <el-form-item label="电话号码" label-width="130px">
          <el-input :model-value="userInfo['phone']" disabled />
        </el-form-item>
        <el-form-item label="公司名称" label-width="130px">
          <el-input :model-value="userInfo['companyName']" disabled />
        </el-form-item>
        <el-form-item label="公司类型" label-width="130px">
          <el-input :model-value="userInfo['companyTypeName']" disabled />
        </el-form-item>
        <el-form-item label="省" label-width="130px">
          <el-input :model-value="userInfo['provinceName']" disabled />
        </el-form-item>
        <el-form-item label="市" label-width="130px">
          <el-input :model-value="userInfo['cityName']" disabled />
        </el-form-item>
        <el-form-item label="区" label-width="130px">
          <el-input :model-value="userInfo['areaName']" disabled />
        </el-form-item>
        <el-form-item label="乡镇" label-width="130px">
          <el-input :model-value="userInfo['townName']" disabled />
        </el-form-item>
        <el-form-item label="主办方" label-width="130px" style="margin-top: 50px;">
          <span>{{ drillInfo.drillSponsor }}</span>
        </el-form-item>
        <el-form-item label="协办方" label-width="130px">
          <span>{{ drillInfo.drillAssist }}</span>
        </el-form-item>
        <el-form-item label="联系人1/联系电话1" label-width="130px">
          <span>{{ `${drillInfo.contactsOne} / ${drillInfo.contactsOnePhone}` }}</span>
        </el-form-item>
        <el-form-item label="联系人1/联系电话1" label-width="130px">
          <span>{{ `${drillInfo.contactsTwo} / ${drillInfo.contactsTwoPhone}` }}</span>
        </el-form-item>
        <el-form-item label="地址" label-width="130px">
          <span>{{ drillInfo.address }}</span>
        </el-form-item>
        <el-form-item label="时间" label-width="130px">
          <span>{{ `${drillInfo.startTime}~${drillInfo.endTime}` }}</span>
        </el-form-item>
        <el-form-item label="活动议程" label-width="130px">
          <span>{{ drillInfo.drillAgenda }}</span>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { FormRules } from "element-plus";
import AccountApi from "~/src/api/AccountApi";
import { useUserStore } from "~/src/store/modules/user";
import confetti from "canvas-confetti";
import { ref, reactive, onMounted, useTemplateRef } from 'vue';  // 确保引入 ref, reactive, onMounted, useTemplateRef
import VDialog from "~/src/utils/dialogUtil";
import SingleLayerSelect from "~/src/templates/components/SingleLayerSelect.vue";

const isSuccess = ref(false);
const form = reactive<Record<string, any>>({});
const url = ref<URL>();
const type = ref("");
const drillId = ref("");
const companyId = ref("");
const formRef = useTemplateRef("formRef");
const userInfo = ref<Record<string, any>>({})
const rule = ref<FormRules>({
  staffName: {
    required: true,
    message: "请输入姓名",
    trigger: "blur",
  },
  staffIdentity: {
    required: true,
    message: "请输入身份证号码",
    trigger: "blur",
  },
});

const drillInfo = ref<Record<any, any>>({})

const store = useUserStore();

onMounted(async () => {
  url.value = new URL(window.location.href);
  console.log("url", url.value);
  type.value = url.value.searchParams.get("type") ?? "";

  if (type.value === 'signup'){

    const obj = {
      phone: {
        required: true,
        message: "请输入手机号",
        trigger: "blur",
      },
      provinceId: {
        required: true,
        message: "请选择省",
        trigger: "blur",
      },
      cityId: {
        required: true,
        message: "请选择市",
        trigger: "blur",
      },
      areaId: {
        required: true,
        message: "请选择区域",
        trigger: "blur",
      },
      townId: {
        required: true,
        message: "请输入乡镇",
        trigger: "blur",
      },
      identityImg: {
        required: true,
        message: "请上传身份证照片",
        trigger: "blur"
      },
      userImg: {
        required: true,
        message: "请上传图片",
        trigger: "blur"
      }
    }

    if(Object.keys(rule.value).includes("phone")) {
      Object.assign(rule.value, obj)
    }
  }
  companyId.value = url.value.searchParams.get("companyId") ?? "";
  drillId.value = url.value.searchParams.get("drillInfoId") ?? "";
  console.log("drillId", drillId.value);

  const res = await AccountApi.getDetail({ drillInfoId: drillId.value })
  res && (drillInfo.value = res.data)
  console.log("drillInfo data", drillInfo.value)
  getProvinceList()
});

const action = (obj: {id?:any, name?:string, type?: any}) => {
  
  const loginForm:Record<any,any> = {}
  if (type.value === 'signup'){
    obj.id && (loginForm.companyId = obj.id)
    obj.type && (loginForm.companyType = obj.type)
    loginForm.companyName = obj.name
    loginForm.staffName = form.staffName
    loginForm.staffIdentity = form.staffIdentity
    loginForm.phone = form.phone
    loginForm.areaId = form.areaId
    loginForm.townId = form.townId
    loginForm.action = "login"
    loginForm.drillId = drillId.value
  } else if (type.value === 'signin') {
    loginForm.staffName = form.staffName
    loginForm.staffIdentity = form.staffIdentity
    loginForm.drillId = drillId.value
  }
  console.log("loginForm",loginForm)
  AccountApi.h5UserLogin(loginForm).then((loginRes) => {
    if (!loginRes || !loginRes.success) {
      return;
    }
    userInfo.value = loginRes.data
    store.setToken(loginRes.data.token);
    console.log("data token", loginRes.data.token);
    if (type.value === "signup") {
      AccountApi.signUp({
        drillId: drillId.value,
        identityImg: form.identityImg,
        userImg: form.userImg
      }).then((res) => {
        if (res && res.success) {
          isSuccess.value = true;
          confetti({
            particleCount: 100,
            spread: 50,
            origin: { y: 0.7 },
          });
        }
      });
    } else if (type.value === "signin") {
      AccountApi.signIn({
        drillId: drillId.value,
      }).then((res) => {
        if (res && res.success) {
          isSuccess.value = true;
          confetti({
            particleCount: 100,
            spread: 50,
            origin: { y: 0.7 },
          });
        }
      });
    }
  })
}
const companyList = ref<{label: any, value: any, type: any}[]>([])

const provinceList = ref([])
const cityList = ref([])
const areaList = ref([])
const townList = ref([])

function getProvinceList() {
  AccountApi.getProvinceList({}).then((res) => {
    provinceList.value = res.data
      .map((item: any) => ({ label: item.province, value: item.provinceId }))
  })
}

function getCityList(v: any) {
  AccountApi.getCityList({ provinceId: v }).then((res) => {
    cityList.value = res.data
      .map((item: any) => ({ label: item.city, value: item.cityId }))
  })
}

function getAreaList(v: any) {
  AccountApi.getNormalAreaList({ cityId: v }).then((res) => {
    areaList.value = res.data
      .map((item: any) => ({ label: item.area, value: item.areaId }))
  })
}

function getTownList(v: any) {
  AccountApi.getTownList({ areaId: v }).then((res) => {
    townList.value = res.data.records
      .map((item: any) => ({ label: item.town, value: item.townId }))
  })
}
const submit = () => {
  console.log("formValue", form);
  formRef.value?.validate((validate) => {
    if (validate) {
      // 不是报名，就直接使用姓名身份证登录
      if (type.value === 'signin') {
        action({}) 
        return
      }
      const companyListItem = {
        staffName: form.staffName,
        staffIdentity: form.staffIdentity,
        phone: form.phone
      }
      AccountApi.getCompanyList(companyListItem).then(res => {
        console.log("res11111", res.data);

        if (res) {
          companyList.value = res.data.map(x => ({ label: x.companyName, value: x.companyId, type: x.companyInfo.type }))

          // 管理端
          if (companyId.value && companyId.value === "0") {

            if (companyList.value.length > 0) {
              if (companyList.value.length === 1) {
                const { value: id, label: name}  = companyList.value[0]
                action({id, name})
              } else {
                VDialog.open({
                  title: "公司选择",
                  content: {
                    top: "35vh",
                    //内容初始形式
                    type: "component", //text:"",预留文本
                    name: "/signin/companySelect",
                    query: { options: companyList }
                  },
                  callBack: ({id, name}:{id: any,name: any}) => {
                    action({id, name})
                  },
                  onClose: () => {
                    console.log("对话框已关闭");
                  },
                });
              }

            } else {
              // $baseMessage("用户不存在", "error")
              VDialog.open({
                title: "公司输入",
                content: {
                  top: "35vh",
                  //内容初始形式
                  type: "component", //text:"",预留文本
                  name: "/signin/company",
                },
                callBack: ({companyName: name, companyType: type}: {companyName: any, companyType: any}) => {
                  action({name, type})
                },
                onClose: () => {
                  console.log("对话框已关闭");
                },
              });
            }

          } else {
            // 商户端
            const currentCompany = companyList.value.find(x=>x.value === companyId.value)
            if (currentCompany) {
              action({id: companyId.value, name: currentCompany.label})
            } else {
              $baseMessage("用户不存在", "error")
            }
          }
        }
      })


    }
  })
}
</script>

<style scoped>
.container {
  padding-top: 100px;
  overflow: scroll;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  /* justify-content: center; */
  align-items: center;
}

:deep(.el-divider__text) {
  font-size: 23px;
  font-weight: 800;
  color: var(--el-color-primary);
}
</style>
